<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/10
 * Time: 17:26
 */

namespace App\Services;

use App\Models\Task;
use App\Models\TaskQuestion;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;

class TaskQuestionService extends BaseService
{
    protected $modelClass = TaskQuestion::class;

    /**
     * 添加
     * @param $postData
     * @return bool|string
     * @throws \Exception
     */
    public function add($postData)
    {
        return $this->saveData($postData);
    }

    /**
     * 编辑
     * @param $id
     * @param $postData
     * @return mixed
     * @throws \Exception
     */
    public function edit($id, $postData)
    {
        try {
            $obj = $this->findByIdOrFail($id);
            if ($obj->update(filter_null($postData))) {
                return $obj;
            }

            return false;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 详情
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function detail1($id)
    {
        try {
            $obj = $this->model
                ->where('id', $id)
                ->with(['attach', 'finishAttach', 'assignUser', 'log'])
                ->first();

            if (!$obj) {
                throw new \Exception('未找到！');
            }

            return $obj;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 删除
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function remove($id)
    {
        try {
            $obj = $this->findByIdOrFail($id);
            if ($obj->process == '进行中') {
                throw new \Exception('不能删除进行中的任务！');
            }

            return $obj->update(['is_enable' => 0]);
        } catch (\Exception $e) {
            throw new \Exception('删除失败！');
        }
    }

    /**
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function cancel($id)
    {
        try {
            $obj = $this->findByIdOrFail($id);
            if ($obj->process != '待开始') {
                throw new \Exception('只能取消待开始状态的任务！');
            }

            return $obj->update([
                'process' => '已取消',
                'user_id' => 0,
                'username' => '',
                'assigned_at' => null,
            ]);
        } catch (\Exception $e) {
            throw new \Exception('操作失败！');
        }
    }

    /**
     * @param $id
     * @param $user_id
     * @return bool|mixed
     * @throws \Exception
     */
    public function start($id, $user_id)
    {
        try {
            $obj = $this->findByIdOrFail($id);
            if ($obj->process != '待开始') {
                throw new \Exception('只能开始待开始的任务！');
            }

            if ($obj->user_id != $user_id) {
                throw new \Exception('只能开始自己的任务！');
            }

            if ($obj->update([
                'process' => '进行中',
            ])) {
                return $obj;
            }

            return false;
        } catch (\Exception $e) {
            throw new \Exception('操作失败！');
        }
    }

    /**
     * @param $id
     * @param $user_id
     * @return bool|mixed
     * @throws \Exception
     */
    public function finish($id, $user_id, $postData)
    {
        try {
            $obj = $this->findByIdOrFail($id);
            if ($obj->process != '进行中') {
                throw new \Exception('只能完成进行中的任务！');
            }

            if ($obj->user_id != $user_id) {
                throw new \Exception('只能完成自己的任务！');
            }

            if ($obj->update([
                'process' => '已完成',
                'finish_attach_id' => $postData['finish_attach_id'],
                'finished_at' => date('Y-m-d H:i:s')
            ])) {
                return $obj;
            }

            return false;
        } catch (\Exception $e) {
            throw new \Exception('操作失败！');
        }
    }

    /**
     * @desc 列表
     * @param array $search
     * @param int $per_page
     * @return array
     */
    public function getList($search=[], $per_page=20)
    {
        $res = $this->model->with(['attach', 'finishAttach', 'assignUser', 'log']);

        if (!empty($search['user_id'])) {
            $res = $res->where('user_id', $search['user_id']);
        }

        if (!empty($search['filename'])) {
            $res = $res->where('filename', 'like', "%{$search['filename']}%");
        }

        if (!empty($search['username'])) {
            $res = $res->where('username', 'like', "%{$search['username']}%");
        }

        if (!empty($search['importance'])) {
            $res = $res->where('importance', $search['importance']);
        }

        if (!empty($search['process'])) {
            $res = $res->where('process', $search['process']);
        }

        if (!empty($search['assignDate'])) {
            $res = $res->whereBetween('assigned_at', $search['assignDate']);
        }

        if (!empty($search['type'])) {
            $res = $res->whereHas('attach', function($query)use($search){
                $query->where('suffix', $search['type']);
            });
        }

        if (!empty($search['sort'])) {
            if ($search['sort'] == '-id') {
                $res = $res->orderBy('id', 'desc');
            } else {
                $res = $res->orderBy('id', 'asc');
            }
        }

        return $this->get_paginate($res->paginate($per_page, ['*']));
    }

    public function info()
    {
        $res = [
            'all' => 0,
            'finish' => 0,
            'unAssign'=> 0,
            'processing' => 0,
        ];

        $obj = $this->getAll(['process']);
        foreach ($obj as $o) {
            if ($o->process == '已完成') {
                $res['finish'] ++;
            }
            if ($o->process == '未指派') {
                $res['unAssign'] ++;
            }
            if ($o->process == '进行中') {
                $res['processing'] ++;
            }

            $res['all'] ++;
        }

        return $res;
    }

    public function grid()
    {
        $grid = new Grid(new TaskQuestion);

        $grid->quickSearch('title');
        $grid->column('id', __('ID'))->sortable();
        $grid->column('title', __('问题'))->filter('like');
        $grid->column('limit_time', __('限时(秒)'));
        $grid->column('type', __('类型'))->filter([
            '单选' => '单选',
            '多选' => '多选',
        ]);
        $grid->column('task.name', __('任务'))->filter('like');
        $grid->column('score', __('分值'));
        $grid->column('created_at', __('创建时间'));
        $grid->filter(function($filter){ // 在这里添加字段过滤器
            $filter->like('title', '问题');
            $filter->where(function ($query) {
                $query->whereHas('task', function ($q) {
                    $q->where('name', 'like', "%{$this->input}%");
                });
            }, '任务');


        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    public function detail($id)
    {
        $show = new Show(TaskQuestion::findOrFail($id));

        $show->field('id', __('ID'));
        $show->field('title', __('问题'));
        $show->field('limit_time', __('限时'));
        $show->field('type', __('类型'));
        $show->field('score', __('分值'));
        $show->field('created_at', __('创建时间'));

        $show->task('所属任务', function ($relation) {
            $relation->setResource('/manager/tasks');
            $relation->field('id', __('ID'));;
            $relation->field('name', __('名称'));;
        });

        $show->anwser('答案选项', function ($relation) {

            $relation->resource('/manager/task-anwsers');

            $relation->column('id', __('ID'));;
            $relation->column('title', __('答案选项'));;
            $relation->column('is_right', __('正确选项?'))->display(function ($column) {
                return $column ? '<span style="color: red;">是</span>' : '否';
            });
        });
        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    public function form()
    {
        $task = Task::query()->pluck('name', 'id')->toArray();
        $states = [
            'on'  => ['value' => '单选', 'text' => '单选', 'color' => 'success'],
            'off' => ['value' => '多选', 'text' => '多选', 'color' => 'danger'],
        ];


        $form = new Form(new TaskQuestion);

        $form->select('task_id', __('所属任务'))->options($task);
        $form->text('title', __('问题'))->rules('required');
        $form->number('score', __('分值'))->rules('required');
        $form->number('limit_time', __('限时(秒)'))->rules('min:0');
        $form->switch('type', __('类型'))->states($states)->default('单选');

        $form->hasMany('anwser', '答案选项', function (Form\NestedForm $form) {


            $form->text('title');
//            $form->switch('is_right', __('正确选项'))->states([
//                'on'  => ['value' => '1', 'text' => '是', 'color' => 'success'],
//                'off' => ['value' => '0', 'text' => '否', 'color' => 'danger'],
//            ])->default('否');
        });

        $form->saved(function (Form $form) {
            // 返回一个简单response
            return redirect('/manager/task-questions');
        });

        return $form;
    }

}